#include <iostream>
#include <string>
#include <brpc/server.h>
#include <butil/logging.h>
#include "main.pb.h"

// 1. 创建rpc服务子类继承pb(protobuf)中的EchoService服务类，并实现内部的业务接口逻辑；
class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl(){}
    ~EchoServiceImpl(){}
    void Echo(google::protobuf::RpcController* controller,
        const ::example::EchoRequest* request,
        ::example::EchoResponse* response,
        ::google::protobuf::Closure* done) override
        {
            //使用ClosureGurd类管理done对象，防止出现未调用Run方法；
            brpc::ClosureGuard rpc_gurd(done);
            std::cout << "收到消息：" << request->message() << std::endl;
            //构建响应
            std::string str = request->message() + "---这是一个响应";
            response->set_message(str);

            // done->Run();
        }
private:

};
int main(int argc, char* argv[])
{
    //关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);
    // 2. 创建rpc服务器类，搭建服务器；
    brpc::Server server;
    // 3. 向服务器类中添加rpc子服务对象---告诉服务器收到什么请求用哪个接口处理；
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1)
    {
        std::cout << "服务添加失败！" << std::endl;
        return -1;
    }
    // 4. 启动服务器
    brpc::ServerOptions options;
    options.idle_timeout_sec = -1;  //连接空闲超时时间---超时后连接关闭
    options.num_threads = 1;    //IO线程数量；
    ret = server.Start(8080, &options);
    if(ret == -1)
    {
        std::cout << "服务器启动失败！" << std::endl;
        return -1;
    }
    // 阻塞等待服务端运行 
    server.RunUntilAskedToQuit();   //休眠等待运行结束
}
